#include "b_config.h"
#include "b_os.h"
#include "ciu32l051_std_flash.h"
#include "hal/inc/b_hal_flash.h"
int bMcuFlashInit()
{
    std_flash_unlock();
    return 0;
}

int bMcuFlashUnlock()
{
    std_flash_unlock();
    return 0;
}

int bMcuFlashLock()
{
    std_flash_lock();
    return 0;
}

int bMcuFlashErase(uint32_t raddr, uint32_t pages)
{
    std_flash_clear_flag(FLASH_FLAG_ALL_ERR);
    bMcuFlashUnlock();
    uint32_t start_page = raddr / 512;          // 计算起始页号
    uint32_t num_pages  = (pages + 511) / 512;  // 向上取整计算需要擦除的页数
    // 检查地址范围是否有效
    if ((raddr + pages) > (std_flash_get_flash_size() * 1024))
    {
        return -1;  // 超出flash大小范围
    }

    // 擦除指定页数
    for (uint32_t i = 0; i < num_pages; i++)
    {
        int ret = std_flash_page_erase(start_page + i);
        if (ret != 0)
        {
            return ret;  // 如果擦除失败则返回错误
     
        }
    }
    bMcuFlashLock();
    return 0;
}

int bMcuFlashWrite(uint32_t raddr, const uint8_t *pbuf, uint32_t len)
{
    if (pbuf == NULL || len == 0 || (raddr & 0x3) != 0) {
        b_log("Invalid parameters: addr:%d len:%d\n", raddr, len);
        return -1;
    }

    bMcuFlashUnlock();
    // 确保长度是4的倍数
    uint32_t aligned_len = (len + 3) & ~0x3;
    uint32_t i;
    uint32_t data;
    
    for (i = 0; i < aligned_len; i += 4) {
        // 安全地读取4个字节
        data = 0;
        for (int j = 0; j < 4 && (i + j) < len; j++) {
            data |= (uint32_t)pbuf[i + j] << (j * 8);
        }
        std_flash_word_program(FLASH_MEM_BASE + raddr + i, data);
    }
    
    bMcuFlashLock();
    return 0;
}

int bMcuFlashRead(uint32_t raddr, uint8_t *pbuf, uint32_t len)
{
    if (pbuf == NULL || (raddr + len) > (std_flash_get_flash_size() * 1024))
    {
        b_log("flash read error addr:%d len:%d\n", raddr, len);
        return -1;
    }
    raddr = FLASH_MEM_BASE + raddr;
    memcpy(pbuf, (const uint8_t *)raddr, len);
    return 0;
}

uint32_t bMcuFlashSectorSize()
{
    return 512;
}

uint32_t bMcuFlashChipSize()
{
    return 512;
}
